﻿using System;

namespace Esponce.QRCode
{
	public class QRCodeHelper
	{
		/// <summary>
		/// Gets a matrix of QR Code modules where "true" means black module and "false" means white module.
		/// </summary>
		/// <param name="ascii">QR Code in ASCII format where 'x' stands for black module, ' ' for white module and optionally '.' for padding.</param>
		/// <param name="includePadding">A value indicating whether padding modules should also be included in output.</param>
		/// <returns>Returns matrix of black and white modules.</returns>
		public static bool[,] GetQRCodeMatrix(string ascii, bool includePadding = false)
		{
			//Keep or remove padding spaces
			ascii = ascii.Replace(".", includePadding ? " " : "");

			//Get rows
			var lines = ascii.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
			int length = lines[0].Length;

			//Convert each char in column/row to bit ('x' for black module, any other for white module)
			bool[,] matrix = new bool[length, length];
			for (int y = 0; y < length; y++)
			{
				for (int x = 0; x < length; x++)
				{
					matrix[x, y] = (lines[y][x] == 'x');
				}
			}

			return matrix;
		}

		/// <summary>
		/// Gets mime type by format.
		/// </summary>
		/// <param name="format">Format name as file extension without dot, e.g. "png"</param>
		/// <returns>Returns mime type for the specified format or "image/png" if format not found.</returns>
		internal static string GetMimeType(string format)
		{
			switch ((format ?? "").ToLower())
			{
				default:
				case "png":
					return "image/png";

				case "jpg":
					return "image/jpeg";

				case "gif":
					return "image/gif";

				case "bmp":
					return "image/bmp";

				case "tif":
					return "image/tiff";

				case "eps":
					return "image/eps"; //Alternative: "application/postscript"

				case "svg":
					return "image/svg+xml";

				case "xaml":
					return "application/xaml+xml";

				case "txt":
					return "text/plain";

				case "html":
					return "text/html";

				case "zip":
					return "application/zip";
			}
		}
	}
}
